/**
 * @file   PutfileCheck.java
 * @date   2012-12-17下午2:55:19
 * @author user
 */
package com.gzceb.zhgjj.filecheck.impl;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.gzceb.zhgjj.filecheck.FileCheck;
import com.gzceb.zhgjj.model.Constants;
import com.gzceb.zhgjj.util.PropertiesUtils;

/**
 * <p>PUTFILE接口卸数错误授权文件校验类。</p>
 *
 * @date   2012-12-17下午2:55:19 
 * @author liqing
 * @description PUTFILE接口中的卸数错误授权文件，在本端响应中心的报文之前，需要校验接收到的
 *              授权文件是否格式正确
 */
public class PutfileCheck implements FileCheck {

	private final Log logger = LogFactory.getLog(getClass());
	protected boolean isNamelegal = false; // 文件名是否合法
	protected String genRecdFlag; // 总记录标志位
	protected String respFileName; // 响应文件名
	protected String recvFileName; // 接收文件名
	protected List<String> fileCont;
	
	
	public PutfileCheck(File file){
		logger.info("the received file name: " + file.getAbsolutePath());
		this.recvFileName = getRecvFileName(file);
		this.isNamelegal = isFormatedName(this.recvFileName)
				&& isDateFormated(this.recvFileName)
				&& isBankCode(this.recvFileName);
		this.setRespFileName();
		this.fileCont = this.getRecvFileCont(file);
	}
	
	private boolean isBankCode(String recvFileName) {
		String bankCode = recvFileName.substring(4, 8);
		//TODO 需完善从配置文件中读取银行代码
		return bankCode.equals(Constants.BANKID); // 是否符合接收银行代码
	}

	private boolean isDateFormated(String recvFileName) {
		String datestr = recvFileName.substring(8, 16);
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
		Date dt;
		try {
			dt = fmt.parse(datestr);
		} catch (Exception ec) {
			return false;
		}
		String tst = fmt.format(dt);
		return datestr.equals(tst);
	}

	public boolean isFormatedName(String recvFileName) {
		Pattern p = Pattern.compile("ER\\d{22}"); // 卸数错误授权文件的文件名
		Matcher m = p.matcher(recvFileName);
		return m.matches();
	}

	/* (non-Javadoc)
	 * @see com.gzceb.zhgjj.filecheck.FileCheck#isNamelegal()
	 */
	@Override
	public boolean isNamelegal() {
		
		return this.isNamelegal;
	}

	/* (non-Javadoc)
	 * @see com.gzceb.zhgjj.filecheck.FileCheck#getRecvFileName(java.io.File)
	 */
	@Override
	public String getRecvFileName(File file) {
		
		return file.getName();
	}

	/* (non-Javadoc)
	 * @see com.gzceb.zhgjj.filecheck.FileCheck#setRespFileName()
	 */
	@Override
	public void setRespFileName() {
		if (this.isNamelegal == true) {
			logger.debug("the file name is legal.");
			this.respFileName = this.recvFileName + "1";
		} else {
			logger.debug("the file name is illegal");
			this.respFileName = this.recvFileName + "0";
		}

	}
	
	/**
	 * 获取响应文件名
	 * @return 文件名 String
	 */
	public String getRespFileName(){
		return this.respFileName;
	}

	/** 创建响应文件
	 * @see com.gzceb.zhgjj.filecheck.FileCheck#crtRespFile()
	 * @return "" 或 响应文件名
	 */
	@Override
	public String crtRespFile() {
		String respFileName = getRespFileName();
		String respFile = PropertiesUtils.getValue("rspPath_PFAuth") + respFileName;
		File file = null;
		try{
			file = new File(respFile);
			if(file.exists()){
				file.delete();	
			}
			file.createNewFile();
		}catch(NullPointerException ne){
			logger.error("errors happened when create response TTF001 file. \n" 
						+ ne.getMessage());
			respFileName = "";
		}catch(IOException ie){
			logger.error("IO errors happened when create response TTF001 file. \n" 
					+ ie.getMessage());
			respFileName = "";
		}
		
		//先设置总记录标志
		setGenRecdFlag();
		
		//生成文件，直接将总记录标识写入到响应文件里
		BufferedWriter writer = null;
		logger.info("begin to create response file...");
		try{
			writer = new BufferedWriter(new FileWriter(file));
			writer.write(this.genRecdFlag);
			
		}catch(IOException ie){
			logger.error("error happend when write the response file.\n" + ie.getMessage());
			respFileName = "";
		}finally{
			if (writer != null) {
				try {
					writer.close();
				} catch (Exception ec) {
					respFileName = "";
				}
			}
		}
		
		return respFileName;
		
	}

	/* (non-Javadoc)
	 * @see com.gzceb.zhgjj.filecheck.FileCheck#getRecvFileCont(java.io.File)
	 */
	@Override
	public List<String> getRecvFileCont(File file) {
		List<String> strarr = new ArrayList<String>();
		BufferedReader reader = null;
		
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempstr = null;
			logger.debug("the file content: \n");
			while ((tempstr = reader.readLine()) != null) {
				strarr.add(tempstr);
				logger.debug(tempstr + "\n");
			}
			
		} catch (IOException e) {
			logger.error("error when read the file " + file.getAbsolutePath()
					+ ":\n" + e);
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (Exception ec) {

				}
			}
		}

		return strarr;
	}

	/* (non-Javadoc)
	 * @see com.gzceb.zhgjj.filecheck.FileCheck#setGenRecdFlag()
	 */
	@Override
	public void setGenRecdFlag() {
		if(true != this.isNamelegal 
				|| !isHeadRight(fileCont)
				){
			this.genRecdFlag = "1";   // 检核失败
		}else{
			this.genRecdFlag = "0";
		}

	}

	/* (non-Javadoc)
	 * @see com.gzceb.zhgjj.filecheck.FileCheck#getGenRecdFlag()
	 */
	@Override
	public String getGenRecdFlag() {
		return this.genRecdFlag;
	}

	/* (non-Javadoc)
	 * @see com.gzceb.zhgjj.filecheck.FileCheck#setEachRecdFlag()
	 */
	@Override
	public void setEachRecdFlag() {
		
	}

	/* (non-Javadoc)
	 * @see com.gzceb.zhgjj.filecheck.FileCheck#getEachRecdFlag(java.util.List)
	 */
	@Override
	public String getEachRecdFlag(List<String> fileCont) {
		// TODO Auto-generated method stub
		return null;
	}

	/* (non-Javadoc)
	 * @see com.gzceb.zhgjj.filecheck.FileCheck#alreadExist(java.lang.String)
	 */
	@Override
	public boolean alreadExist(String contCode) {
		// TODO Auto-generated method stub
		return true;
	}
	
	/**
	 * 卸数错误的授权文件中头部的总记录格式校验. 		
	 * @作者   		liqing
	 * @创建日期 	2012-11-13 22:51 
	 * @param fileCont List<String>
	 * @throws none
	 * @return boolean
	 */
	public  boolean isHeadRight(List<String> fileCont) {
		/*
		 * 文件中的第一行信息为登记总笔数，格式：序号|记录总数|日期
		 */
		String tmpStr = fileCont.get(0);
		Pattern p = Pattern.compile("\\d{0,5}\\|\\d+\\|\\d{8}\\|"); // 卸数错误授权文件的文件名
		Matcher m = p.matcher(tmpStr);
		if (m.matches()) {
			return true;
		} else {
			return false;
		}
	}
	
	
	
	public static void main(String[] args){
		List<String> fileCont =new ArrayList<String>();
		fileCont.add("12345|3|20120405");
		//isHeadRight(fileCont);
		String destPath = "C:\\Documents and Settings\\user\\Workspaces\\MyEclipse 10\\.metadata\\.me_tcat\\webapps\\HousingFund\\dailydata\\PUTFILE\\receival\\";
		String fileName = "test"; 
		File file = new File(destPath + fileName);
		String test = file.getName();
		
	}

}
